package modules.arc.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import luxing.common.controller.BaseController;
import luxing.exception.BusinessException;
import luxing.hibernate.CriteriaQuery;
import luxing.util.CriteriaQueryUtil;
import luxing.util.ValidatorUtil;
import luxing.web.model.DataGrid;
import luxing.web.model.Result;
import luxing.web.model.ValidResult;
import modules.arc.entity.ArcExt;
import modules.arc.entity.Driver;
import modules.arc.entity.Owner;
import modules.arc.entity.OwnerExt;
import modules.arc.entity.Vehicle;
import modules.arc.service.ArcExtService;
import modules.arc.service.DriverService;
import modules.arc.service.OwnerService;
import modules.arc.service.VehicleService;
import modules.fin.entity.IncomeSum;
import modules.fin.entity.OutlaySum;
import modules.fin.service.IncomeService;
import modules.fin.service.OutlayService;
import modules.loan.entity.LoanContract;
import modules.loan.service.LoanContractService;
import modules.sys.entity.Log;
import modules.sys.service.LogService;

/**
 * 
 * @author zzc
 *
 */
@Controller
@RequestMapping("/ownerController")
public class OwnerController extends BaseController {

	private static final Logger logger = Logger.getLogger(OwnerController.class);

	@Autowired
	private LogService logService;
	@Autowired
	private OwnerService ownerService;
	@Autowired
	private DriverService driverService;
	@Autowired
	private VehicleService vehicleService;
	@Autowired
	private ArcExtService arcExtService;
	@Autowired
	private LoanContractService loanContractService;
	@Autowired
	private IncomeService incomeService;
	@Autowired
	private OutlayService outlayService;

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "index")
	public ModelAndView index(HttpServletRequest request) {
		return new ModelAndView("modules/arc/owner-list");
	}

	/**
	 * 责任人车辆列表页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "ownerVehicleIndex")
	public ModelAndView ownerVehicleIndex(HttpServletRequest request) {
		request.setAttribute("ownerId", request.getParameter("ownerId"));
		return new ModelAndView("modules/arc/ownerVehicle-list");
	}

	/**
	 * 列表选择页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "select")
	public ModelAndView select(HttpServletRequest request) {
		return new ModelAndView("modules/arc/owner-select");
	}

	/**
	 * 增加页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(HttpServletRequest req) {
		return new ModelAndView("modules/arc/owner-add");
	}

	/**
	 * 修改页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(Owner owner, HttpServletRequest req) {
		if (StringUtils.isNotBlank(owner.getId())) {
			owner = ownerService.get(Owner.class, owner.getId());
			req.setAttribute("ownerPage", owner);
		}
		return new ModelAndView("modules/arc/owner-update");
	}

	/**
	 * 详情页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goDetail")
	public ModelAndView goDetail(Owner owner, HttpServletRequest req) {
		if (StringUtils.isNotBlank(owner.getId())) {
			owner = ownerService.get(Owner.class, owner.getId());
			req.setAttribute("ownerPage", owner);
		}
		return new ModelAndView("modules/arc/owner-detail");
	}

	/**
	 * 责任人车辆绑定页面
	 * 
	 * @return
	 */
	@RequestMapping(params = "goBind")
	public ModelAndView goBind(HttpServletRequest req) {
		req.setAttribute("ownerId", req.getParameter("ownerId"));
		return new ModelAndView("modules/arc/ownerVehicle-bind");
	}

	/**
	 * 扩展信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "ext")
	public ModelAndView ext(Owner OwnerEntity, HttpServletRequest req) {
		req.setAttribute("id", req.getParameter("id"));
		req.setAttribute("type",
				req.getParameter("type") == null ? ArcExt.TYPE_OWNER_DRIVER : req.getParameter("type"));
		return new ModelAndView("modules/arc/owner-ext");
	}

	/**
	 * 列表数据
	 * 
	 * @param owner
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "list")
	public void list(Owner owner, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Owner.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, owner, request.getParameterMap());
			// 状态
			String status = request.getParameter("status");
			status = StringUtils.isBlank(status) ? Owner.STATUS_ENABLE : status;
			cq.eq("status", status);
			cq.add();
			ownerService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("责任人查询失败", e);
			throw new BusinessException("责任人查询失败", e);
		}
	}

	/**
	 * 责任人-车辆列表数据
	 * 
	 * @param vehicle
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "ownerVehicleList")
	public void ownerVehicleList(Vehicle vehicle, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Vehicle.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicle, request.getParameterMap());
			cq.eq("owner.id", request.getParameter("ownerId"));
			cq.add();
			vehicleService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("车辆查询失败", e);
			throw new BusinessException("车辆查询失败", e);
		}
	}

	/**
	 * 责任人-车辆绑定列表数据
	 * 
	 * @param vehicle
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "ownerVehicleBindList")
	public void ownerVehicleBindList(Vehicle vehicle, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {
		try {
			CriteriaQuery cq = new CriteriaQuery(Vehicle.class, dataGrid);
			CriteriaQueryUtil.assembling(cq, vehicle, request.getParameterMap());
			cq.notEq("owner.id", request.getParameter("ownerId"));
			// 状态
			String status = request.getParameter("status");
			if (StringUtils.isBlank(status)) {
				cq.notEq("status", Vehicle.STATUS_DISABLE);
			}
			cq.add();
			vehicleService.listByPage(cq, true);
			listView(response, dataGrid);
		} catch (Exception e) {
			logger.error("车辆查询失败", e);
			throw new BusinessException("车辆查询失败", e);
		}
	}

	/**
	 * 增加
	 * 
	 * @param owner
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public Result doAdd(Owner owner, HttpServletRequest request) {
		String msg = null;
		String type = request.getParameter("type");
		try {
			owner.setStatus(Owner.STATUS_ENABLE);
			// bean校验
			msg = ValidatorUtil.validate(owner);
			if (StringUtils.isNotBlank(msg)) {
				return Result.error(msg);
			}
			if (type.equals(ArcExt.TYPE_OWNER_DRIVER)) {
				// 责任人兼司机
				ownerService.save(owner, arcExtService.listByType(ArcExt.TYPE_OWNER),
						new Driver(owner.getName(), owner.getSex(), owner.getPhone(), owner.getIdCard(),
								owner.getAddress(), Driver.STATUS_ENABLE, owner.getRemarks()),
						arcExtService.listByType(ArcExt.TYPE_DRIVER), request);
			} else {
				// 责任人
				ownerService.save(owner, arcExtService.listByType(ArcExt.TYPE_OWNER), request);
			}
			if (type.equals(ArcExt.TYPE_OWNER_DRIVER)) {
				msg = "责任人兼司机\"" + owner.getName() + "\"增加成功";
			} else {
				msg = "责任人\"" + owner.getName() + "\"增加成功";
			}
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_ADD);
		} catch (Exception e) {
			if (type.equals(ArcExt.TYPE_OWNER_DRIVER)) {
				msg = "责任人兼司机\"" + owner.getName() + "\"增加失败";
			} else {
				msg = "责任人\"" + owner.getName() + "\"增加失败";
			}
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 车辆-责任人绑定
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "doBind")
	@ResponseBody
	public Result doBind(HttpServletRequest req) {
		String msg = null;
		try {
			Owner owner = ownerService.get(Owner.class, req.getParameter("ownerId"));
			String vehicleIds = req.getParameter("vehicleIds");
			if (owner != null && StringUtils.isNotBlank(vehicleIds)) {
				for (String vehicleId : vehicleIds.split(",")) {
					Vehicle vehicle = vehicleService.get(Vehicle.class, vehicleId);
					vehicle.setOwner(owner);
					vehicleService.saveOrUpdate(vehicle);
				}
			}
			msg = "车辆-责任人,绑定成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "车辆-责任人,绑定失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 修改
	 * 
	 * @param owner
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public Result doUpdate(Owner owner, HttpServletRequest request) {
		String msg = null;
		try {
			// TODO
			// 注销时判断是否有未还欠款
			//
			// 档案扩展
			List<ArcExt> arcExtList = arcExtService.listByType(ArcExt.TYPE_OWNER);
			List<OwnerExt> ownerExtList = new ArrayList<OwnerExt>();
			for (ArcExt arcExt : arcExtList) {
				String value = request.getParameter(arcExt.getId());
				if (StringUtils.isNotBlank(value)) {
					OwnerExt ownerExt = new OwnerExt();
					ownerExt.setOwnerId(owner.getId());
					ownerExt.setArcExtId(arcExt.getId());
					ownerExt.setValue(value);
					ownerExtList.add(ownerExt);
				}
			}
			ownerService.update(owner, ownerExtList);
			msg = "责任人\"" + owner.getName() + "\"修改成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_UPDATE);
		} catch (Exception e) {
			msg = "责任人\"" + owner.getName() + "\"修改失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 删除
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public Result doDel(Owner owner, HttpServletRequest request) {
		String msg = null;
		try {
			owner = ownerService.get(Owner.class, owner.getId());
			// 关联车辆
			if (CollectionUtils.isNotEmpty(owner.getVehicleList())) {
				msg = "责任人\"" + owner.getName() + "\"有关联车辆,无法删除";
				return Result.error(msg);
			}
			// 贷款管理
			List<LoanContract> loanContractList = loanContractService.listByOwner(owner.getId());
			if (CollectionUtils.isNotEmpty(loanContractList)) {
				msg = "责任人\"" + owner.getName() + "\"有关联贷款,无法删除";
				return Result.error(msg);
			}
			// 收款记录
			List<IncomeSum> incomeSumList = incomeService.listByOwner(owner.getId());
			if (CollectionUtils.isNotEmpty(incomeSumList)) {
				msg = "责任人\"" + owner.getName() + "\"有关联收款,无法删除";
				return Result.error(msg);
			}
			// 付款记录
			List<OutlaySum> outlaySumList = outlayService.listByOwner(owner.getId());
			if (CollectionUtils.isNotEmpty(outlaySumList)) {
				msg = "责任人\"" + owner.getName() + "\"有关联付款,无法删除";
				return Result.error(msg);
			}

			ownerService.delete(owner);
			msg = "责任人\"" + owner.getName() + "\"删除成功";
			logger.info(msg);
			logService.addLogInfo(msg, Log.OPERATE_DEL);
		} catch (Exception e) {
			msg = "责任人\"" + owner.getName() + "\"删除失败";
			logger.error(msg, e);
			throw new BusinessException(msg, e);
		}
		return Result.success(msg);
	}

	/**
	 * 姓名change ajax
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "nameChange")
	@ResponseBody
	public Result nameChange(HttpServletRequest req) {
		Result result = new Result();
		Map<String, Object> attributes = new HashMap<String, Object>();
		String name = req.getParameter("name");
		Driver driver = driverService.getByName(name);
		if (driver != null) {
			attributes.put("exist", "yes");
		} else {
			attributes.put("exist", "no");
		}
		result.setAttributes(attributes);
		return result;
	}

	/**
	 * 手机change ajax
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "phoneChange")
	@ResponseBody
	public Result phoneChange(HttpServletRequest req) {
		Result result = new Result();
		Map<String, Object> attributes = new HashMap<String, Object>();
		String phone = req.getParameter("phone");
		Driver driver = driverService.getByPhone(phone);
		if (driver != null) {
			attributes.put("exist", "yes");
		} else {
			attributes.put("exist", "no");
		}
		result.setAttributes(attributes);
		return result;
	}

	/**
	 * 身份证change ajax
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "idCardChange")
	@ResponseBody
	public Result idCardChange(HttpServletRequest req) {
		Result result = new Result();
		Map<String, Object> attributes = new HashMap<String, Object>();
		String idCard = req.getParameter("idCard");
		Driver driver = driverService.getByIdCard(idCard);
		if (driver != null) {
			attributes.put("exist", "yes");
		} else {
			attributes.put("exist", "no");
		}
		result.setAttributes(attributes);
		return result;
	}

	/**
	 * 姓名校验
	 */
	@RequestMapping(params = "validName")
	@ResponseBody
	public ValidResult validName(HttpServletRequest request) {
		ValidResult result = new ValidResult();
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		Owner owner = ownerService.getByName(name);
		if (id == null) {
			// 增加
			if (owner != null) {
				result.setInfo("姓名已存在");
				result.setStatus("n");
			}
		} else {
			// 修改
			if (owner != null && !owner.getId().equals(id)) {
				result.setInfo("姓名已存在");
				result.setStatus("n");
			}
		}
		return result;
	}

	/**
	 * 手机校验
	 */
	@RequestMapping(params = "validPhone")
	@ResponseBody
	public ValidResult validPhone(HttpServletRequest request) {
		ValidResult result = new ValidResult();
		String id = request.getParameter("id");
		String phone = request.getParameter("phone");
		Owner owner = ownerService.getByPhone(phone);
		if (id == null) {
			// 增加
			if (owner != null) {
				result.setInfo("手机已存在");
				result.setStatus("n");
			}
		} else {
			// 修改
			if (owner != null && !owner.getId().equals(id)) {
				result.setInfo("手机已存在");
				result.setStatus("n");
			}
		}
		return result;
	}

	/**
	 * 身份证校验
	 */
	@RequestMapping(params = "validIdCard")
	@ResponseBody
	public ValidResult validIdCard(HttpServletRequest request) {
		ValidResult result = new ValidResult();
		String id = request.getParameter("id");
		String idCard = request.getParameter("idCard");
		Owner owner = ownerService.getByIdCard(idCard);
		if (id == null) {
			// 增加
			if (owner != null) {
				result.setInfo("身份证已存在");
				result.setStatus("n");
			}
		} else {
			// 修改
			if (owner != null && !owner.getId().equals(id)) {
				result.setInfo("身份证已存在");
				result.setStatus("n");
			}
		}
		return result;
	}

}
